package pattern.email;

import org.hazlewood.connor.bottema.emailaddress.EmailAddressCriteria;
import org.hazlewood.connor.bottema.emailaddress.EmailAddressValidator;
import org.simplejavamail.api.email.Email;
import org.simplejavamail.api.mailer.config.TransportStrategy;
import org.simplejavamail.email.EmailBuilder;
import org.simplejavamail.mailer.MailerBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.EnumSet;
import java.util.List;

/**
 *  邮件发送
 * @author admin
 */
@Component
public class EmailSendTool {

    @Value(value = "${email.address}")
    private String address;
    @Value(value = "${email.pwd}")
    private String pwd;
    @Value(value = "${email.title}")
    private String title;

   /*
    kefu_Aik518
    */

    /**
     * 发送批量邮件
     */
    public void batchSend(List<SendEmailModel> modelList){
        modelList.forEach(this::send);
    }


    /**
     * 发送单个邮件 使用阿里企业邮箱
     */
    public String send(SendEmailModel sendEmailModel){
        var valid = EmailAddressValidator.isValid(address,
                EnumSet.of(EmailAddressCriteria.ALLOW_QUOTED_IDENTIFIERS, EmailAddressCriteria.ALLOW_PARENS_IN_LOCALPART));
        if (valid) {
            Email email = EmailBuilder.startingBlank()
                    .from("Pisces", address)
                    .to(sendEmailModel.getName(), sendEmailModel.getAddress())
                    .withSubject(title)
                    .withHTMLText(sendEmailModel.getContent())
                    .buildEmail();
            MailerBuilder
                    .withSMTPServer("smtp.qiye.aliyun.com", 465, address, pwd)
                    .withTransportStrategy(TransportStrategy.SMTPS)
//                    .withProxy("socksproxy.host.com", 1080, "proxy user", "proxy password")
                    .buildMailer().sendMail(email);
            return "";
        }else{
            return "邮箱格式错误";
        }
    }

    public static void main(String[] args) {
        Email email = EmailBuilder.startingBlank()
                .from("admin", "kefu@域名")
                .to("simon", "934907236@qq.com")
                .withSubject("pattern")
                .withHTMLText("test")
                .buildEmail();
        MailerBuilder
                .withSMTPServer("smtp.qiye.aliyun.com", 465, "kefu@域名.com", "Syz123456.")
                .withTransportStrategy(TransportStrategy.SMTPS)
//                    .withProxy("socksproxy.host.com", 1080, "proxy user", "proxy password")
                .buildMailer().sendMail(email);
    }
}
